package com.xywl.escort.view.market;

import android.graphics.Bitmap;
import android.graphics.Paint;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.view.OnApplyWindowInsetsListener;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.WindowInsetsCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.listener.OnItemClickListener;
import com.just.agentweb.AgentWeb;
import com.just.agentweb.DefaultWebClient;
import com.trello.rxlifecycle2.LifecycleTransformer;
import com.xywl.escort.R;
import com.xywl.escort.adapter.EvaluateAdapter;
import com.xywl.escort.adapter.NetworkImageHolderView;
import com.xywl.escort.base.BaseActivity;
import com.xywl.escort.bean.AddShoppingCartReq;
import com.xywl.escort.bean.BaseResp;
import com.xywl.escort.bean.BaseSkuModel;
import com.xywl.escort.bean.CommentsReq;
import com.xywl.escort.bean.CommentsResp;
import com.xywl.escort.bean.GoodDetailResp;
import com.xywl.escort.bean.ShoppingCartResp;
import com.xywl.escort.bean.SpecResp;
import com.xywl.escort.common.Constant;
import com.xywl.escort.utils.NetworkUtil;
import com.xywl.escort.utils.NumberFormatUtils;
import com.xywl.escort.utils.RxSPTool;
import com.xywl.escort.utils.ToastUtil;
import com.xywl.escort.view.market.skus.BodyPopWindow;
import com.xywl.escort.view.market.skus.ItemClickListener;
import com.xywl.escort.view.market.skus.ProductModel;
import com.xywl.escort.view.market.skus.SkuAdapter;
import com.xywl.escort.view.market.skus.SkuUtil;
import com.xywl.escort.view.market.skus.UiData;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import dagger.android.AndroidInjection;
import timber.log.Timber;

import static com.xywl.escort.common.PreferenceKeys.TOKEN;

/**
 * 商品详情
 */
@Route(path = "/xy/product/detail")
public class ProductDetailsActivity extends BaseActivity implements ProductDetailsContract.View, BodyPopWindow.OnItemClickListener {

    @BindView(R.id.progress_bar)
    ProgressBar mProgressBar;
    @BindView(R.id.layout_bottom_tools)
    LinearLayout mLayoutBottomTools;
    @BindView(R.id.convenientBanner)
    ConvenientBanner mConvenientBanner;
    @BindView(R.id.text_shelves)
    TextView mTextShelves;
    @BindView(R.id.recycler_evaluate)
    RecyclerView mRecyclerEvaluate;
    @BindView(R.id.text_ship_detail)
    TextView mTextShipDetail;
    @BindView(R.id.appbar)
    AppBarLayout mAppbar;
    @BindView(R.id.layout_webView)
    LinearLayout mLayoutWebView;
    @BindView(R.id.layout_content)
    CoordinatorLayout mLayoutContent;
    @BindView(R.id.btn_add_shopping)
    Button mBtnAddShopping;
    @BindView(R.id.btn_payment)
    Button mBtnPayment;
    @BindView(R.id.text_product_specification)
    TextView mTextProductSpecification;
    @BindView(R.id.root_container_layout)
    RelativeLayout mLayoutProduct;
    @BindView(R.id.text_product_name)
    TextView mTextProductName;
    @BindView(R.id.text_product_sold)
    TextView mTextProductSold;
    @BindView(R.id.text_price)
    TextView mTextPrice;
    @BindView(R.id.text_original_price)
    TextView mTextOriginalPrice;

    private AgentWeb mAgentWeb;
    private int state = 0;
    private EvaluateAdapter mAdapter;
    private List<CommentsResp.DataBean.ListBean> mDataBeanList = new ArrayList<>();

    @Inject
    ProductDetailsContract.Presenter mPresenter;

    private String mIconUrl;

    @Autowired
    String spuId;
    @Autowired
    String skuId;

    private UiData mUiData;
    private ProductModel product;

    private int mType = 1;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        AndroidInjection.inject(this);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_product_details);
        ARouter.getInstance().inject(this);
        ButterKnife.bind(this);
        showBackButton();
        setTitleText(R.string.product_detail);
        View view = findViewById(R.id.root_container_layout);
        if (null != view) {
            // TODO Android沉浸式状态栏
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                ViewCompat.setOnApplyWindowInsetsListener(view, new OnApplyWindowInsetsListener() {
                    @Override
                    public WindowInsetsCompat onApplyWindowInsets(View v, WindowInsetsCompat insets) {
                        return insets.consumeSystemWindowInsets();
                    }
                });
            }
        }
        mAdapter = new EvaluateAdapter(R.layout.item_product_evaluate, mDataBeanList);
        mRecyclerEvaluate.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerEvaluate.setAdapter(mAdapter);

        mPresenter.takeView(this);
        mPresenter.loadProductDetails(spuId, skuId);

        mAgentWeb = AgentWeb.with(this)
                .setAgentWebParent(mLayoutWebView, new LinearLayout.LayoutParams(-1, -1))
                .useDefaultIndicator()
                .setWebChromeClient(mWebChromeClient)
                .setWebViewClient(mWebViewClient)
                .setMainFrameErrorView(R.layout.agentweb_error_page, -1)
                .setSecurityType(AgentWeb.SecurityType.STRICT_CHECK)
                .setOpenOtherPageWays(DefaultWebClient.OpenOtherPageWays.ASK)//打开其他应用时，弹窗咨询用户是否前往其他应用
                .interceptUnkownUrl() //拦截找不到相关页面的Scheme
                .createAgentWeb()
                .ready()
                .go(getUrl(spuId));

        mAppbar.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                if (verticalOffset == 0) {
                    if (state != Constant.CollapsingToolbarLayoutState.EXPANDED) {
                        // 修改状态标记为展开
                        mTextShipDetail.setVisibility(View.GONE);
                        state = Constant.CollapsingToolbarLayoutState.EXPANDED;
                    }
                } else if (Math.abs(verticalOffset) >= appBarLayout.getTotalScrollRange()) {
                    if (state != Constant.CollapsingToolbarLayoutState.COLLAPSED) {
                        // 修改状态标记为折叠
                        mTextShipDetail.setVisibility(View.VISIBLE);
                        state = Constant.CollapsingToolbarLayoutState.COLLAPSED;
                    }
                }
            }
        });
    }

    private WebViewClient mWebViewClient = new WebViewClient() {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            return super.shouldOverrideUrlLoading(view, request);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }
    };

    private WebChromeClient mWebChromeClient = new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
        }
    };

    private String getUrl(String spuId) {
        return "http://statich5.nmbjvip.com/description.html?id=" + spuId;
    }

    @Override
    public void loadSpecificSuccess(SpecResp.DataBean dataBean) {
        initData(dataBean);
    }

    @Override
    public void loadSpecificFailure(String msg) {
        Timber.tag("ProductDetailsActivity").e("loadSpecificFailure");
        ToastUtil.showTip(this, msg);
    }

    @Override
    public void updateProductDetails(GoodDetailResp.DataBean dataBean) {
        mProgressBar.setVisibility(View.GONE);
        mLayoutContent.setVisibility(View.VISIBLE);
        mLayoutBottomTools.setVisibility(View.VISIBLE);

        updateBanner(dataBean);

        if (dataBean.status == 1) {
            mTextShelves.setVisibility(View.GONE);
            mBtnAddShopping.setEnabled(true);
            mBtnPayment.setEnabled(true);
            mTextProductSpecification.setEnabled(true);
        } else {
            mTextShelves.setVisibility(View.VISIBLE);
            mBtnAddShopping.setEnabled(false);
            mBtnPayment.setEnabled(false);
            mTextProductSpecification.setEnabled(false);
        }

        mTextProductName.setText(dataBean.spuName);
        String sold = "总销量：" + dataBean.sold + "份";
        mTextProductSold.setText(sold);
        if (null != dataBean.price) {
            String price = "￥" + NumberFormatUtils.getInstance().format2Decimal(dataBean.price.doubleValue());
            mTextPrice.setText(price);
        }
        if (null != dataBean.originalPrice) {
            String originalPrice = "￥" + NumberFormatUtils.getInstance().format2Decimal(dataBean.originalPrice.doubleValue());
            mTextOriginalPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
            mTextOriginalPrice.setText(originalPrice);
        }
    }

    @Override
    public void loadProductDetailsFailure() {
        mProgressBar.setVisibility(View.GONE);
        mLayoutContent.setVisibility(View.VISIBLE);
        mLayoutBottomTools.setVisibility(View.VISIBLE);
    }

    @Override
    public void addShoppingCartSuccess(BaseResp resp) {
        ToastUtil.showTip(this, "添加宝箱成功");
    }

    @Override
    public void addShoppingCartFailure(String msg) {
        ToastUtil.showTip(this, msg);
    }

    @Override
    public void loadCommentsSuccess(CommentsResp.DataBean dataBean) {
        mDataBeanList.clear();
        if (dataBean.list.size() > 0) {
            mDataBeanList.add(dataBean.list.get(0));
        }
        mAdapter.setNewData(mDataBeanList);
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void loadCommentsFailure() {
        Timber.tag("ProductDetailsActivity").e("loadCommentsFailure");
    }

    private void updateBanner(final GoodDetailResp.DataBean dataBean) {
        if (null != dataBean && null != dataBean.images) {
            List<GoodDetailResp.DataBean.ImagesBean> list = dataBean.images;
            List<String> bannerList = new ArrayList<>();
            for (GoodDetailResp.DataBean.ImagesBean bean : list) {
                bannerList.add(bean.imageUrl);
                if (bean.type == 1) {
                    mIconUrl = bean.imageUrl;
                }
            }
            mConvenientBanner.setPages(new CBViewHolderCreator() {
                @Override
                public NetworkImageHolderView createHolder() {
                    return new NetworkImageHolderView();
                }
            }, bannerList).setPageIndicator(new int[]{
                    R.mipmap.home_banner2,
                    R.mipmap.home_banner1})
                    .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.CENTER_HORIZONTAL)
                    .setCanLoop(bannerList.size() > 1);
            if (bannerList.size() > 1) {
                mConvenientBanner.startTurning(5000);
            }
        }
    }

    @Override
    public boolean isActive() {
        return false;
    }

    @Override
    public <T> LifecycleTransformer<T> bindToLife() {
        return this.<T>bindToLifecycle();
    }

    @OnClick({R.id.text_product_specification, R.id.btn_add_shopping, R.id.btn_payment, R.id.text_evaluate})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.text_product_specification: {
                spec(1);
            }
            break;
            case R.id.btn_add_shopping: {
                String token = RxSPTool.getString(this, TOKEN);
                if (!TextUtils.isEmpty(token)) {
                    spec(2);
                } else {
                    ToastUtil.showTip(this, "用户未登录");
                    ARouter.getInstance().build("/xy/login").navigation();
                }
            }
            break;
            case R.id.btn_payment: {
                String token = RxSPTool.getString(this, TOKEN);
                if (!TextUtils.isEmpty(token)) {
                    spec(3);
                } else {
                    ToastUtil.showTip(this, "用户未登录");
                    ARouter.getInstance().build("/xy/login").navigation();
                }
            }
            break;
            case R.id.text_evaluate: {
                ARouter.getInstance().build("/xy/product/evaluate").withString("spuId", spuId).navigation();
            }
            break;
            default:
                break;
        }
    }

    private void spec(int type) {
        if (!NetworkUtil.isAvailable(this)) {
            ToastUtil.showTip(this, R.string.network_error);
            return;
        }
        mType = type;
        mPresenter.loadSpecific(spuId, skuId);
    }

    @Override
    public void onPause() {
        mAgentWeb.getWebLifeCycle().onPause();
        super.onPause();
    }

    @Override
    protected void onResume() {
        mAgentWeb.getWebLifeCycle().onResume();
        super.onResume();
        CommentsReq req = new CommentsReq();
        req.pageNum = 1;
        req.pageSize = 1;
        req.spuId = spuId;
        mPresenter.loadComments(req);
    }

    @Override
    protected void onDestroy() {
        mAgentWeb.getWebLifeCycle().onDestroy();
        super.onDestroy();
        mConvenientBanner.stopTurning();
    }

    private void initData(SpecResp.DataBean goodsBean) {
        mUiData = new UiData();
        product = new ProductModel();
        BaseSkuModel baseSkuModel = new BaseSkuModel();
        baseSkuModel.id = goodsBean.spuId;
        baseSkuModel.spuName = goodsBean.spuName;
        baseSkuModel.price = goodsBean.minPrice;
        baseSkuModel.originalPrice = goodsBean.maxPrice;
        baseSkuModel.picture = mIconUrl;
        baseSkuModel.stock = goodsBean.stock;
        mUiData.baseSkuModel = baseSkuModel;
        List<SpecResp.DataBean.SpuSpecPropertysBean> spuSpecPropertys = goodsBean.spuSpecPropertys;
        boolean isSpecSmall = false;
        for (int i = 0; i < spuSpecPropertys.size(); i++) {
            if (checkIsEmpty(goodsBean, i)) {
                break;
            }
            spuSpecPropertys.get(i).spuSpecPropertyValues = SkuUtil.ifRepeat(spuSpecPropertys.get(i).spuSpecPropertyValues);
            ProductModel.AttributesEntity group01 = new ProductModel.AttributesEntity();
            group01.name = goodsBean.spuName;

            for (int j = 0; j < spuSpecPropertys.get(i).spuSpecPropertyValues.size(); j++) {
                group01.attributeMembers.add(j, new ProductModel.AttributesEntity.AttributeMembersEntity(i, (j + 1 + i * 10), spuSpecPropertys.get(i).spuSpecPropertyValues.get(j).value));
            }
            product.attributes.add(i, group01);// 第一组
            String projectName = spuSpecPropertys.get(i).name;
            mUiData.projectType.add(i, projectName);
        }
        for (int i = 0; i < goodsBean.skus.size(); i++) {
            List<String> data = new ArrayList<>();
            String[] strings = SkuUtil.convertStrToArray(goodsBean.skus.get(i).skuName);
            if (null != strings) {
                for (String string : strings) {
                    if (string.length() != 0) {
                        data.add(string);
                    }
                }
            }
            StringBuilder stringBuilder = new StringBuilder();
            for (int z = 0; z < data.size(); z++) {
                if (spuSpecPropertys.size() <= z) {
                    break;
                }
                SpecResp.DataBean.SpuSpecPropertysBean specPropertysBean = spuSpecPropertys.get(z);
                if (null == specPropertysBean) {
                    break;
                }
                List<SpecResp.DataBean.SpuSpecPropertysBean.SpuSpecPropertyValuesBean> spuSpecPropertyValues = specPropertysBean.spuSpecPropertyValues;
                if (null == spuSpecPropertyValues) {
                    break;
                }
                if (spuSpecPropertyValues.size() == 0) {
                    isSpecSmall = true;
                }
                for (int d = 0; d < spuSpecPropertyValues.size(); d++) {
                    if (TextUtils.equals(data.get(z), spuSpecPropertys.get(z).spuSpecPropertyValues.get(d).value)) {
                        stringBuilder.append((d + 1 + z * 10));
                        stringBuilder.append(";");
                    }
                }
            }
            if (stringBuilder.length() != 0) {
                String skuName = stringBuilder.substring(0, stringBuilder.length() - 1);
                BaseSkuModel skuModel = new BaseSkuModel();
                skuModel.price = goodsBean.skus.get(i).price;
                skuModel.originalPrice = goodsBean.skus.get(i).originalPrice;
                skuModel.stock = goodsBean.skus.get(i).stock;
                skuModel.spuId = goodsBean.skus.get(i).spuId;
                skuModel.spuName = goodsBean.spuName;
                skuModel.id = goodsBean.skus.get(i).id;
                skuModel.skuName = goodsBean.skus.get(i).skuName;
                skuModel.picture = mIconUrl;
                product.productStocks.put(skuName, skuModel);
            }
        }
        Timber.e(product.toString());

        showPopWindow(isSpecSmall);
    }

    /**
     * 初始化按钮的状态（没有该规格或者库存为0的设置为不可点击）
     */
    private void initDataTwo() {
        for (int i = 0; i < mUiData.adapters.size(); i++) {
            for (ProductModel.AttributesEntity.AttributeMembersEntity entity : mUiData.adapters.get(i).getAttributeMembersEntities()) {
                if (mUiData.result.get(entity.attributeMemberId + "") == null
                        || mUiData.result.get(entity.attributeMemberId + "").stock <= 0) {
                    entity.status = 2;
                }
            }
        }
    }

    /**
     * 检查这个数据是否大小为0或者是否为null
     *
     * @param dataBean
     * @param i
     * @return boolean
     */
    private boolean checkIsEmpty(SpecResp.DataBean dataBean, int i) {
        return TextUtils.isEmpty(dataBean.spuSpecPropertys.get(i).name)
                && (dataBean.spuSpecPropertys.get(i).spuSpecPropertyValues == null
                || dataBean.spuSpecPropertys.get(i).spuSpecPropertyValues.size() == 0);
    }

    private void showPopWindow(boolean isSpecSmall) {
        if (mUiData.mBottomSheetDialog == null) {
            mUiData.selectedEntities.clear();
            mUiData.adapters.clear();
            //添加list组
            for (int i = 0; i < product.attributes.size(); i++) {
                SkuAdapter skuAdapter = new SkuAdapter(product.attributes.get(i).attributeMembers);
                mUiData.adapters.add(skuAdapter);
            }
            // SKU 计算
            mUiData.result = SkuUtil.skuCollection(product.productStocks);
            //设置点击监听器
            for (SkuAdapter adapter : mUiData.adapters) {
                ItemClickListener listener = new ItemClickListener(mUiData, adapter);
                adapter.setOnClickListener(listener);
            }
            // 初始化按钮
            initDataTwo();
            mUiData.mBottomSheetDialog = new BodyPopWindow(ProductDetailsActivity.this, mUiData, mType, isSpecSmall);
        }
        SkuUtil.setBabyShowData(mUiData);
        mUiData.mBottomSheetDialog.showAsDropDown(mLayoutProduct);
        mUiData.mBottomSheetDialog.setOnItemClickListener(this);
    }

    @Override
    public void onClickShopping(long num) {
        if (!NetworkUtil.isAvailable(this)) {
            ToastUtil.showTip(this, R.string.network_error);
            return;
        }
        Timber.tag("onClickShopping").e(mUiData.currentSkuModel.toString());
        Timber.tag("onClickShopping").e("" + num);
        String token = RxSPTool.getString(this, TOKEN);
        if (!TextUtils.isEmpty(token)) {
            BaseSkuModel skuModel = mUiData.currentSkuModel;
            AddShoppingCartReq req = new AddShoppingCartReq();
            req.spuId = skuModel.spuId;
            req.spuName = skuModel.spuName;
            req.skuId = skuModel.id;
            req.skuName = skuModel.skuName;
            req.amount = num;
            req.price = skuModel.price;
            req.imageUrl = skuModel.picture;
            mPresenter.addShoppingCart(req);
        } else {
            ToastUtil.showTip(this, "用户未登录");
            ARouter.getInstance().build("/xy/login").navigation();
        }
    }

    @Override
    public void onClickBuy(long num) {
        if (!NetworkUtil.isAvailable(this)) {
            ToastUtil.showTip(this, R.string.network_error);
            return;
        }
        Timber.tag("onClickBuy").e(mUiData.currentSkuModel.toString());
        Timber.tag("onClickBuy").e("" + num);
        String token = RxSPTool.getString(this, TOKEN);
        if (!TextUtils.isEmpty(token)) {
            BaseSkuModel skuModel = mUiData.currentSkuModel;
            List<ShoppingCartResp.DataBean> list = new ArrayList<>();
            ShoppingCartResp.DataBean dataBean = new ShoppingCartResp.DataBean();
            dataBean.spuId = skuModel.spuId;
            dataBean.skuId = skuModel.id;
            dataBean.skuName = skuModel.skuName;
            dataBean.spuName = skuModel.spuName;
            dataBean.price = skuModel.price;
            dataBean.originalPrice = skuModel.originalPrice;
            dataBean.spuName = skuModel.spuName;
            dataBean.imageUrl = skuModel.picture;
            dataBean.amount = new BigDecimal(num);
            list.add(dataBean);

            ARouter.getInstance().build("/xy/order/submit")
                    .withObject("list", list)
                    .navigation();
        } else {
            ToastUtil.showTip(this, "用户未登录");
            ARouter.getInstance().build("/xy/login").navigation();
        }
    }

    @Override
    public void cancel() {

    }
}
